package me.chan.nio.channel;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo {

    public static void main(String[] args) throws IOException {

        URL url = Thread.currentThread().getContextClassLoader().getResource("file.txt");

        String path = url.getPath();
        try(FileChannel channel = new FileInputStream(path).getChannel()) {
            ByteBuffer buffer = ByteBuffer.allocate(10);

            while (true) {

                int size = channel.read(buffer);
                if (size <= 0)     // implies nothing left in channel
                    break;

                System.out.printf("have read %d bytes", size);
                System.out.println();

                buffer.flip();
                while (buffer.hasRemaining()) {
                    System.out.println((char) buffer.get());
                }

                buffer.clear();
            }
        } finally {

        }
    }
}
